package cn.com.xiaoshoujia.order.controller;

import cn.com.xiaoshoujia.activities.dto.ActivityOrderWxDTO;
import cn.com.xiaoshoujia.activities.entity.Activity;
import cn.com.xiaoshoujia.activities.service.ActivitiesService;
import cn.com.xiaoshoujia.application.service.SMSService;
import cn.com.xiaoshoujia.domain.enums.MsgValidateCodeConstants;
import cn.com.xiaoshoujia.order.entity.Order;
import cn.com.xiaoshoujia.order.mapper.ActivityOrderMapper;
import cn.com.xiaoshoujia.order.service.OrderService;
import cn.com.xiaoshoujia.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@RestController
public class OrderController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private ActivitiesService activitiesService;

    @Autowired
    private SMSService smsService;

    @Autowired
    private ActivityOrderMapper activityOrderMapper;

    /**
     * @Author: yangrui
     * @Description: wx保存订单
     * 需判断
     * 拼团活动删除、暂停、过期状态
     * 团是否成功
     * @Date: 下午4:12 2017/8/3
     */
    @PostMapping(value = "saveOrder")
    public Object saveOrder(@Valid Order order, BindingResult result, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        logger.info("team wx saveOrder start");
        if (result.hasFieldErrors()) {
            logger.info("team wx saveOrder fielderrors {}", result.getFieldError().getDefaultMessage());
            return SALES.encryption(httpServletRequest, httpServletResponse, new Result("FAIL", result.getFieldError().getDefaultMessage()));
        }
        Long fkActivitiesId = order.getFkActivitiesId();
        Activity activity = activitiesService.findWxStatusById(fkActivitiesId);
        if (activity.getStatus() == GeneralConstants.ACTIVITY_DELETE_STATUS) {
            logger.info("team wx saveOrder 该拼团活动已被删除");
            return SALES.encryption(httpServletRequest, httpServletResponse, new Result("FAIL", "该拼团活动已被删除"));
        }
        if (activity.getActivitiesStatus() == GeneralConstants.ACTIVITY_STOP_STATUS) {
            logger.info("team wx saveOrder 该拼团活动暂停中");
            return SALES.encryption(httpServletRequest, httpServletResponse, new Result("FAIL", "该拼团活动暂停中"));
        }
        if (activity.getActivitiesStatus() == GeneralConstants.ACTIVITY_OVERTIME_STATUS) {
            logger.info("team wx saveOrder 该拼团活动已过期");
            return SALES.encryption(httpServletRequest, httpServletResponse, new Result("FAIL", "该拼团活动已过期"));
        }
        /*join start*/
        boolean aBoolean = orderService.save(order);
        if (aBoolean) {
            logger.info("team wx saveOrder end {}", aBoolean);
            return SALES.encryption(httpServletRequest, httpServletResponse, new Result("SUCCESS", "成功"));
        } else {
            logger.info("team wx saveOrder end {}", aBoolean);
            return SALES.encryption(httpServletRequest, httpServletResponse, new Result("FAIL", "系统异常"));
        }
        /*join end*/
    }

    private Integer checkActivityStatus(Activity activity) {
        if (activity.getStatus() == GeneralConstants.ACTIVITY_DELETE_STATUS) {
            logger.info("team wx saveOrder 该拼团活动已被删除");
            return GeneralConstants.ACTIVITY_DELETE_STATUS;
        }
        if (activity.getActivitiesStatus() == GeneralConstants.ACTIVITY_STOP_STATUS) {
            logger.info("team wx saveOrder 该拼团活动暂停中");
            return GeneralConstants.ACTIVITY_STOP_STATUS;
        }
        if (activity.getActivitiesStatus() == GeneralConstants.ACTIVITY_OVERTIME_STATUS) {
            logger.info("team wx saveOrder 该拼团活动已过期");
            return GeneralConstants.ACTIVITY_OVERTIME_STATUS;
        }
        return null;
    }

    /**
     * @Author: dulei
     * @Description: 参团接口
     * @Date: 2017/8/6 19:48
     */
    @PostMapping("team/teamOrder")
    public Object teamOrder(String pkProduct, @Valid ActivityOrderWxDTO wxOrder, BindingResult result,
                            HttpServletRequest request, HttpServletResponse response) {
        if (result.hasErrors()) {
            logger.error("param errors");
            return SALES.encryption(request, response, new Result("FAIL","错误请求", 10));
        }
        logger.info("check message code");
        String smsresult = smsService.checkValidateCode(wxOrder.getCluesPhone(), MsgValidateCodeConstants.MsgValidateCodeType.SIGIN, wxOrder.getIdentifyingCode());
        if (StringUtils.isNotBlank(smsresult)) {
            logger.info(smsresult);
            return SALES.encryption(request, response, new Result("FAIL", smsresult, 13));
        }
        //判断活动状态
        Activity activity = activitiesService.findWxStatusById(wxOrder.getId());
        String currentTime = DateUtils.getCurrentTime();
        if (currentTime.compareTo(activity.getStartTime())<0){
            return SALES.encryption(request, response, new Result("FAIL", "活动尚未开始", null));
        }
        if (currentTime.compareTo(activity.getEndTime())>0){
            return SALES.encryption(request, response, new Result("FAIL", "活动已经结束", null));
        }
        Integer activityStatus = checkActivityStatus(activity);
        if (activityStatus != null)
            return SALES.encryption(request, response, new Result("FAIL", "活动结束", activityStatus));
        //判断团的状态
        if (wxOrder.getType().intValue() == 3) {
            if (null == wxOrder.getHeadId())
                return SALES.encryption(request, response, new Result("FAIL", "参数错误", 10));
            Integer wxHeadStatus = orderService.findWxHeadStatus(wxOrder.getHeadId());
            if (wxHeadStatus.intValue() == -1)
                return SALES.encryption(request, response, new Result("FAIL", "团已失败", wxHeadStatus.intValue() + 4));
            if (wxHeadStatus.intValue() == 0){
                return SALES.encryption(request, response, new Result("FAIL", "团长尚未支付", wxHeadStatus.intValue() + 4));
            }
            if (wxHeadStatus.intValue() == 3){
                return SALES.encryption(request, response, new Result("FAIL", "团长已经成功", wxHeadStatus.intValue() + 4));
            }
        }
        //进行参数编码
        try {
            wxOrder.setUserName(URLEncoder.encode(wxOrder.getUserName(), "utf-8"));
            wxOrder.setValueJson(URLEncoder.encode(wxOrder.getValueJson(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("error username encode utf-8");
            return SALES.encryption(request, response, new Result("FAIL", "系统错误", 11));
        }

        Long productId = activityOrderMapper.findIdByXcode(pkProduct);
        logger.info("team wx productId {}",productId);
        boolean boo = false;
        try {
            boo = orderService.saveTeamOrder(wxOrder, productId);
            if (!boo) {
                return SALES.encryption(request, response, new Result("FAIL", "保存失败", 12));
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return SALES.encryption(request, response, new Result("FAIL", "系统异常", 12));
        }
        return SALES.encryption(request, response, new Result("SUCCESS", boo));
    }

    /**
     * @Author: dulei
     * @Description: 根据订单号 取消订单
     * @param:  * @param null
     * @Date: 2017/8/10 14:32
     */
    @GetMapping("team/cancelOrder")
    public Object cancelOrder(String orderId, HttpServletRequest request, HttpServletResponse response) {

        if (StringUtils.isBlank(orderId)) {
            logger.error("param is error");
            return SALES.encryption(request, response, new Result("FAIL", "参数错误", null));
        }
        boolean b = false;
        try {
            b = orderService.cancelOrder(orderId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return SALES.encryption(request, response, new Result("FAIL", "取消失败", null));
        }
        if (!b)
            return SALES.encryption(request, response, new Result("FAIL", "无此订单", null));
        return SALES.encryption(request, response, new Result("SUCCESS", null));
    }

    @GetMapping("team/noPayOrder")
    public Object noPayOrder(String sysId,Long id,HttpServletRequest request, HttpServletResponse response){
        if (StringUtils.isBlank(sysId)||null==id){
            logger.error("数据为null sysId = {},id = {}",sysId,id);
            return SALES.encryption(request, response, new Result("FAIL", "请求失败", null));
        }
        Map map = orderService.findNoPayOrder(sysId,id);
        return SALES.encryption(request, response, new Result("SUCCESS", map));
    }
}
